package com.tapadoo.alerter;

/*
 * Copyright 2013 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Modifications Copyright (C) 2017 David Kwon
 */


import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.VelocityDetector;
import ohos.multimodalinput.event.TouchEvent;

class SwipeDismissTouchListener implements Component.TouchEventListener {
    // Cached ViewConfiguration and system-wide constant values
    private  int mSlop;
    private  int mMinFlingVelocity;
    private final long mAnimationTime;

    // Fixed properties
    private final Component mView;
    private final DismissCallbacks mCallbacks;
    private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero

    // Transient properties
    private float mDownX;
    private float mDownY;
    private boolean mSwiping;
    private int mSwipingSlop;
    private Object mToken;
    private VelocityDetector mVelocityTracker;
    private float mTranslationX;

    /**
     * Constructs a new swipe-to-dismiss touch listener for the given view.
     *
     * @param view     The view to make dismissable.
     * @param token    An optional token/cookie object to be passed through to the callback.
     * @param callbacks The callback to trigger when the user has indicated that she would like to
     *                 dismiss this view.
     */
    SwipeDismissTouchListener(Component view, Object token, DismissCallbacks callbacks) {
//        ViewConfiguration vc = ViewConfiguration.get(view.getContext());
//        mSlop = vc.getScaledTouchSlop();
//        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
        mAnimationTime = 200;
        mView = view;
        mToken = token;
        mCallbacks = callbacks;
    }


    private void performDismiss() {
        // Animate the dismissed view to zero-height and then fire the dismiss callback.
        // This triggers layout on each animation frame; in the future we may want to do something
        // smarter and more performant.

        final ComponentContainer.LayoutConfig lp = mView.getLayoutConfig();
        final int originalHeight = mView.getHeight();

        AnimatorValue animator = new AnimatorValue();

        animator.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {

            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                mCallbacks.onDismiss(mView, mToken);
                // Reset view presentation
                mView.setAlpha(1f);
                mView.setTranslationX(0);
                lp.height = originalHeight;
                mView.setLayoutConfig(lp);
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });

        animator.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                lp.height = (int)v;
                mView.setLayoutConfig(lp);
            }
        });

        animator.start();
    }

    @Override
    public boolean onTouchEvent(Component component, TouchEvent motionEvent) {
        motionEvent.setScreenOffset(mTranslationX, 0);

        if (mViewWidth < 2) {
            mViewWidth = mView.getWidth();
        }

        switch (motionEvent.getAction()) {
            case TouchEvent.PRIMARY_POINT_DOWN: {
                mDownX = motionEvent.getPointerScreenPosition(0).getX();
                mDownY = motionEvent.getPointerScreenPosition(0).getY();
                if (mCallbacks.canDismiss(mToken)) {
                    mVelocityTracker = VelocityDetector.obtainInstance();
                    mVelocityTracker.addEvent(motionEvent);
                }
                mCallbacks.onTouch(mView, true);
                return false;
            }

            case TouchEvent.PRIMARY_POINT_UP: {
                if (mVelocityTracker == null) {
                    break;
                }

                float deltaX = motionEvent.getPointerScreenPosition(0).getX() - mDownX;
                mVelocityTracker.addEvent(motionEvent);
                mVelocityTracker.calculateCurrentVelocity(1000);
                float velocityX = mVelocityTracker.getHorizontalVelocity();
                float absVelocityX = Math.abs(velocityX);
                float absVelocityY = Math.abs(mVelocityTracker.getVerticalVelocity());
                boolean dismiss = false;
                boolean dismissRight = false;
                if (Math.abs(deltaX) > mViewWidth / 2 && mSwiping) {
                    dismiss = true;
                    dismissRight = deltaX > 0;
                } else if (mMinFlingVelocity <= absVelocityX && absVelocityY < absVelocityX && mSwiping) {
                    // dismiss only if flinging in the same direction as dragging
                    dismiss = (velocityX < 0) == (deltaX < 0);
                    dismissRight = mVelocityTracker.getHorizontalVelocity() > 0;
                }
                if (dismiss) {
                    // dismiss
//                    mView.animate()
//                            .translationX(dismissRight ? mViewWidth : -mViewWidth)
//                            .alpha(0)
//                            .setDuration(mAnimationTime)
//                            .setListener(new AnimatorListenerAdapter() {
//                                @Override
//                                public void onAnimationEnd(Animator animation) {
//                                    performDismiss();
//                                }
//                            });
                    performDismiss();
                } else if (mSwiping) {
                    // cancel
//                    mView.animate()
//                            .translationX(0)
//                            .alpha(1)
//                            .setDuration(mAnimationTime)
//                            .setListener(null);
                    mCallbacks.onTouch(mView, false);
                }
                mVelocityTracker.clear();
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;

                break;
            }

            case TouchEvent.CANCEL: {
                if (mVelocityTracker == null) {
                    break;
                }

//                mView.animate()
//                        .translationX(0)
//                        .alpha(1)
//                        .setDuration(mAnimationTime)
//                        .setListener(null);
//                mVelocityTracker.recycle();
                mVelocityTracker = null;
                mTranslationX = 0;
                mDownX = 0;
                mDownY = 0;
                mSwiping = false;
                break;
            }

            case TouchEvent.POINT_MOVE: {
                if (mVelocityTracker == null) {
                    break;
                }

                mVelocityTracker.addEvent(motionEvent);
                float deltaX = motionEvent.getPointerScreenPosition(0).getX() - mDownX;
                float deltaY = motionEvent.getPointerScreenPosition(0).getY() - mDownY;
                if (Math.abs(deltaX) > mSlop && Math.abs(deltaY) < Math.abs(deltaX) / 2) {
                    mSwiping = true;
                    mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
//                    mView.getParent().requestDisallowInterceptTouchEvent(true);

                    // Cancel listview's touch
//                    MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
//                    cancelEvent.setAction(MotionEvent.ACTION_CANCEL
//                            | (motionEvent.getActionIndex()
//                            << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
//                    mView.onTouchEvent(cancelEvent);
//                    cancelEvent.recycle();
                }

                if (mSwiping) {
                    mTranslationX = deltaX;
                    mView.setTranslationX(deltaX - mSwipingSlop);
                    // TODO: use an ease-out interpolator or such
                    mView.setAlpha(Math.max(0f, Math.min(1f,
                            1f - 2f * Math.abs(deltaX) / mViewWidth)));
                    return true;
                }
                break;
            }

            default: {
                mView.callOnClick();
                return false;
            }
        }
        return false;
    }

    interface DismissCallbacks {

        boolean canDismiss(Object token);

        void onDismiss(Component view, Object token);

        void onTouch(Component view, boolean touch);
    }
}